import { GetTokenApi } from '@/apis/user'
import { setCache, removeCache } from '@/utils/cache'
import { defineStore } from 'pinia'
import { CACHE_KEY } from '@/enums/cacheEnum'
import { router } from '@/router'

export const useUserStore = defineStore('user', {
  state: () => {
    return {
      userInfo: {},
      token: ''
    }
  },
  getters: {
    getUserInfo(state) {
      return state.userInfo
    }
  },
  actions: {
    async Login(params: LoginParams) {
      const { token, userInfo } = (await GetTokenApi(params)) as any

      setCache(CACHE_KEY.TOKEN, token, 60 * 60 * 24 * 7)
      setCache(CACHE_KEY.USER_INFO, userInfo, 60 * 60 * 24 * 7)
      this.token = token
      this.userInfo = userInfo
      return userInfo
    },
    async Logout() {
      removeCache(CACHE_KEY.TOKEN)
      removeCache(CACHE_KEY.USER_INFO)
      this.token = ''
      this.userInfo = {}
      router.replace({
        name: 'login'
      })
    }
  }
})
